<template>
    <div class="search">
        <div class="search-input">
            <input 
            v-model="keyword"
            type="text" placeholder="输入您要搜索的城市">
        </div>  
        <div class="wrapper" ref="wrapper" v-show="keyword">      
            <ul  >
                <li v-for="(item,index) of list" :key="index"  @click="handleClick(item.name)" >{{item.name}}</li>
                <li v-show="!list.length">没有你想要的城市</li>
            </ul>
        </div>
    </div>
</template>
<script>
import BScroll from "better-scroll";
export default {
  name: "CitySearch",
  props: ["cities"],
  data() {
    return {
      keyword: "",
      // 接收能够搜索到的数据
      list: []
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.scroll = new BScroll(this.$refs.wrapper, {});
    });
  },
  watch: {
    keyword() {
      if (!this.keyword) {
        this.list = [];
        return;
      }
      var result = [];
      for (const i in this.cities) {
        this.cities[i].forEach(ele => {
          if (
            ele.spell.startsWith(this.keyword) ||
            ele.name.startsWith(this.keyword)
          ) {
            result.push(ele);
          }
        });
      }
      this.list = result;
    }
  },
  methods: {
    handleClick(event) {
      this.$store.commit("changeCity",event)
      this.$router.push("/")
      this.keyword = ""
    }
  }
};
</script>
<style lang="scss" scoped>
.search {
  background: #fff;
  z-index: 100;
  position: fixed;
  top: 81px;
  left: 0px;
  width: 100%;
  .search-input {
    padding: 10px 0;
    height: 60px;
    background: #00bcd4;
    text-align: center;
    input {
      width: 90%;
      line-height: 60px;
      border-radius: 15px;
      outline: none;
      padding-left: 20px;
      border-style: none;
    }
  }
  .wrapper {
    width: 100%;
    height: 1150px;
    overflow: hidden;
    position: relative;
    padding: 20px;
    li {
      border-bottom: 1px solid#eee;
      line-height: 54px;
    }
  }
}
</style>
